import App from './App.vue'

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'

// 引入网络请求库
import { $http } from '@escook/request-miniprogram'
uni.$http = $http

// 导入工具类
import http from './common/http.js'
import dateUtils from './common/dateUtils.js'
import { isLoggedIn } from './common/utils/auth.js'
import { syncStorageToStore } from './common/utils/store-helper.js'

// 导入状态管理
import store from './store'
import pinia from './store/piniaIndex.js'

// 确保全局可以访问pinia
if (typeof getApp !== 'undefined') {
  const globalApp = getApp()
  if (globalApp) {
    if (!globalApp.$pinia) {
      globalApp.$pinia = pinia
    }
    if (!globalApp.globalData) {
      globalApp.globalData = {}
    }
    globalApp.globalData.pinia = pinia
  }
}

// 注册全局过滤器
import * as filters from './common/filters.js'
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

// 添加全局混入，检查登录状态
Vue.mixin({
  onShow() {
    // 尝试同步本地存储到Pinia
    try {
      syncStorageToStore()
    } catch (error) {
      console.error('页面显示时同步存储失败:', error)
    }
    
    // 获取当前页面路径
    const pages = getCurrentPages()
    if (pages.length > 0) {
      const currentPage = pages[pages.length - 1]
      const path = `/${currentPage.route}`
      
      // 白名单页面无需登录
      const whiteList = ['/pages/login/index', '/pages/privacy/index']
      if (!whiteList.some(item => path.startsWith(item))) {
        // 检查是否已登录
        if (!isLoggedIn()) {
          // 未登录，提示并跳转到登录页
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          
          // 延迟跳转，让用户看到提示
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/index'
            })
          }, 1500)
          
          return false
        }
      }
    }
  },
  
  mounted() {
    // 在组件挂载时尝试同步本地存储到Pinia
    setTimeout(() => {
      try {
        syncStorageToStore()
      } catch (error) {
        console.error('组件挂载时同步存储失败:', error)
      }
    }, 300)
  }
})

// 注册uni-ui组件
import uniCard from '@dcloudio/uni-ui/lib/uni-card/uni-card.vue'
import uniSection from '@dcloudio/uni-ui/lib/uni-section/uni-section.vue'
import uniCalendar from '@dcloudio/uni-ui/lib/uni-calendar/uni-calendar.vue'
import uniEasyinput from '@dcloudio/uni-ui/lib/uni-easyinput/uni-easyinput.vue'
import uniDataPicker from '@dcloudio/uni-ui/lib/uni-data-picker/uni-data-picker.vue'
import uniDatetimePicker from '@dcloudio/uni-ui/lib/uni-datetime-picker/uni-datetime-picker.vue'
// 使用TDesign图标代替uni-icons
// import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

Vue.component('uni-card', uniCard)
Vue.component('uni-section', uniSection)
Vue.component('uni-calendar', uniCalendar)
Vue.component('uni-easyinput', uniEasyinput)
Vue.component('uni-data-picker', uniDataPicker)
Vue.component('uni-datetime-picker', uniDatetimePicker)
// Vue.component('uni-icons', uniIcons)

// 挂载工具到全局
Vue.prototype.$http = http
Vue.prototype.$date = dateUtils

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
  ...App,
  store
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
import { ensureRouteExists } from './common/utils/helper.js'
// 导入Pinia状态管理
import pinia from './store/piniaIndex.js'
// 导入环境修复工具
import { fixRouteUndefined, injectGlobalVariables } from './common/utils/mpFix.js'
// 导入数据同步服务
import dataSyncService from './common/services/dataSync.js'
// 导入登录检查工具
import { isLoggedIn } from './common/utils/auth.js'
// 导入安全访问Pinia工具
import { syncStorageToStore } from './common/utils/store-helper.js'

// 全局错误处理
const handleError = (err) => {
  console.error('应用发生错误:', err)
  
  // 修复__route__未定义问题
  if (err && err.message && err.message.includes('__route__ is not defined')) {
    ensureRouteExists()
    fixRouteUndefined()
  }
  
  // 修复store未定义问题
  if (err && err.message && err.message.includes('store is not defined')) {
    injectGlobalVariables()
  }
  
  // 修复pinia问题
  if (err && err.message && err.message.includes('getActivePinia')) {
    console.warn('检测到Pinia激活问题，尝试修复...')
    // 尝试使用备用存储
    syncStorageToStore()
  }
}

export function createApp() {
  const app = createSSRApp(App)
  
  // 添加全局错误处理
  app.config.errorHandler = handleError
  
  // 在应用启动时初始化路由和环境变量
  ensureRouteExists()
  fixRouteUndefined()
  injectGlobalVariables()
  
  // 添加Pinia
  app.use(pinia)
  
  // 确保全局可以访问Pinia
  if (typeof getApp !== 'undefined') {
    const globalApp = getApp()
    if (globalApp) {
      if (!globalApp.$pinia) {
        globalApp.$pinia = pinia
      }
      if (!globalApp.globalData) {
        globalApp.globalData = {}
      }
      globalApp.globalData.pinia = pinia
    }
  }
  
  // 向全局注入pinia实例
  app.config.globalProperties.$pinia = pinia
  
  // 注册数据同步服务
  app.config.globalProperties.$dataSync = dataSyncService
  
  // 添加全局混入，检查登录状态和同步数据
  app.mixin({
    onShow() {
      // 尝试同步本地存储到Pinia
      try {
        syncStorageToStore()
      } catch (error) {
        console.error('页面显示时同步存储失败:', error)
      }
      
      // 获取当前页面路径
      const pages = getCurrentPages()
      if (pages.length > 0) {
        const currentPage = pages[pages.length - 1]
        const path = `/${currentPage.route}`
        
        // 白名单页面无需登录
        const whiteList = ['/pages/login/index', '/pages/privacy/index']
        if (!whiteList.some(item => path.startsWith(item))) {
          // 检查是否已登录
          if (!isLoggedIn()) {
            // 未登录，提示并跳转到登录页
            uni.showToast({
              title: '请先登录',
              icon: 'none'
            })
            
            // 延迟跳转，让用户看到提示
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/login/index'
              })
            }, 1500)
            
            return false
          }
        }
      }
    },
    
    mounted() {
      // 在组件挂载时尝试同步本地存储到Pinia
      setTimeout(() => {
        try {
          syncStorageToStore()
        } catch (error) {
          console.error('组件挂载时同步存储失败:', error)
        }
      }, 300)
    }
  })
  
  return {
    app
  }
}
// #endif